<?php
/**
 * User: zhangligang
 * Email: tzhang2450@163.com
 * Date: 2018/12/29
 * Time: 13:26
 */

namespace App\Services;


use App\Models\Advice;
use App\Models\Contest;
use App\Models\Department;
use App\Models\GrowRule;
use App\Models\IncreaseScoreApply;
use App\Models\MemberFileScore;
use App\Models\ScoreFile;
use App\Models\User;
use App\Models\Manager;
use App\Models\UserLevel;
use App\Providers\MyJwt;

class ManagerService extends Service
{
    public static function getUsers($limit, $offset, $role = 0, $search = '')
    {
        $year = date('Y', time());
        $query = User::where('is_del', 0);
        if ($role > 0) {
            $query = $query->where('role', $role);
        }
        if ($search) {
            $query = $query->where('realname', 'like', "%{$search}%");
        }
        $total = $query->count();
        $users = $query->orderBy('id', 'desc')->limit($limit)->offset($offset)->get();
        $result = [];
        foreach ($users as $user) {
            $department = Department::where('id', $user->department_id)->first();
            $score = 0;
            $applyScores = IncreaseScoreApply::where('is_del', 0)->where('role', 1)->where('user_id', $user->id)->where('department_id', $user->department_id)->where('created_at', '>=', $year.'-01-01 00:00:00')->get();
            foreach ($applyScores as $applyScore) {
                $score += $applyScore->score;
            }
            $memberScoreFiles = MemberFileScore::where('is_del', 0)->where('role', 1)->where('type', 3)->where('user_id', $user->id)->where('created_at', '>=', $year.'-01-01 00:00:00')->get();
            foreach ($memberScoreFiles as $memberScoreFile) {
                $score += $memberScoreFile->score*0.9;
            }
            $result[] = [
                'id' => $user->id,
                'realname' => $user->realname,
                'department_id' => $user->department_id,
                'department_name' => $department ? $department->name : '',
                'score' => $score,
                'role' => $user->role,
                'level' => self::getUserYearLevel($user->id, $year)
            ];
        }
        return [
            'total' => $total,
            'rows' => $result,
            'pages' => ceil($total / $limit),
            'page' => $offset / $limit + 1
        ];
    }

    public static function getDepartments($limit, $offset, $search = '')
    {
        $year = date('Y', time());
        $query = Department::where('is_del', 0);
        if ($search) {
            $query = $query->where('name', 'like', "%{$search}%");
        }
        $total = $query->count();
        $departments = $query->orderBy('id', 'desc')->limit($limit)->offset($offset)->get();
        $result = [];
        foreach ($departments as $department) {
            $score = 0;
            $applyScores = IncreaseScoreApply::where('is_del', 0)->where('role', 2)->where('department_id', $department->id)->where('created_at', '>=', $year.'-01-01 00:00:00')->get();
            foreach ($applyScores as $applyScore) {
                $score += $applyScore->score;
            }
            $memberScoreFiles = MemberFileScore::where('is_del', 0)->where('role', 2)->where('type', 3)->where('department_id', $department->id)->where('created_at', '>=', $year.'-01-01 00:00:00')->get();
            foreach ($memberScoreFiles as $memberScoreFile) {
                $score += $memberScoreFile->score;
            }
            $result[] = [
                'id' => $department->id,
                'name' => $department->name,
                'score' => $score
            ];
        }
        return [
            'total' => $total,
            'rows' => $result,
            'pages' => ceil($total / $limit),
            'page' => $offset / $limit + 1
        ];
    }

    public static function getDepartmentDetail($departmentId)
    {
        $year = date('Y', time());
        $department = Department::where('is_del', 0)->where('id', $departmentId)->first();
        if (!$department) {
            return [];
        }
        $members = [];
        $users = User::where('is_del', 0)->where('department_id', $departmentId)->orderBy('id', 'desc')->limit(5)->get();
        foreach ($users as $user) {
            $members[] = [
                'id' => $user->id,
                'realname' => $user->realname
            ];
        }
        $score = 0;
        $applyScores = IncreaseScoreApply::where('is_del', 0)->where('role', 2)->where('department_id', $departmentId)->where('created_at', '>=', $year.'-01-01 00:00:00')->get();
        foreach ($applyScores as $applyScore) {
            $score += $applyScore->score;
        }
        $memberScoreFiles = MemberFileScore::where('is_del', 0)->where('role', 2)->where('type', 3)->where('department_id', $departmentId)->where('created_at', '>=', $year.'-01-01 00:00:00')->get();
        foreach ($memberScoreFiles as $memberScoreFile) {
            $score += $memberScoreFile->score;
        }

        return [
            'id' => $department->id,
            'name' => $department->name,
            'found_at' => date('Y-m-d', strtotime($department->found_at)),
            'members' => $members,
            'score' => $score,
            'desc' => $department->desc,
            'summary' => $department->summary
        ];
    }

    public static function deleteDepartment($departmentId)
    {
        $department = Department::where('is_del', 0)->where('id', $departmentId)->first();
        if ($department) {
            $department->is_del = 1;
            $department->updated_at = date('Y-m-d H:i:s', time());
            $department->save();
        }
        $manager = Manager::where('is_del', 0)->where('department_id', $departmentId)->first();
        if ($manager) {
            $manager->is_del = 1;
            $manager->updated_at = date('Y-m-d H:i:s', time());
            $manager->save();
        }
    }

    public static function getManagers($limit, $offset, $role = 0, $search = '')
    {
        $query = Manager::where('is_del', 0);
        if ($role) {
            $query = $query->where('role', $role);
        }
        if ($search) {
            $query = $query->where('realname', 'like', "%{$search}%");
        }
        $total = $query->count();
        $managers = $query->orderBy('id', 'desc')->limit($limit)->offset($offset)->get();
        $result = [];
        foreach ($managers as $manager) {
            $result[] = [
                'id' => $manager->id,
                'username' => $manager->username,
                'realname' => $manager->realname,
                'role' => $manager->role,
                'role_name' => $manager->role == 1 ? '党委' : '党支部',
                'department_id' => $manager->department_id
            ];
        }
        return [
            'total' => $total,
            'rows' => $result,
            'limit' => $limit,
            'offset' => $offset,
            'page' => ceil($total / $limit),
            'pageNumber' => $offset / $limit + 1
        ];
    }

    public static function getManagerDetail($id)
    {
        $manager = Manager::where('is_del', 0)->where('id', $id)->first();
        if (!$manager) {
            return [];
        }
        return [
            'id' => $manager->id,
            'username' => $manager->username,
            'realname' => $manager->realname,
            'role' => $manager->role,
            'role_name' => $manager->role == 1 ? '党委' : '党支部',
            'department_id' => $manager->department_id
        ];
    }

    public static function saveManager($data)
    {
        if (array_key_exists('id', $data)) {
            $manager = Manager::where('id', $data['id'])->first();
        } else {
            $manager = new Manager();
            $manager->created_at = date('Y-m-d H:i:s', time());
        }
        foreach ($data as $key => $value) {
            if ($key == 'department_name') {
                $department = new Department();
                $department->name = $value;
                $department->desc = '';
                $department->summary = '';
                $department->created_at = date('Y-m-d H:i:s', time());
                $department->updated_at = date('Y-m-d H:i:s', time());
                $department->save();
                $manager->department_id = $department->id;
            } else {
                $manager->$key = $value;
            }
        }
        $manager->updated_at = date('Y-m-d H:i:s', time());
        $manager->save();
    }

    public static function getSimpleDepartments()
    {
        $departments = Department::where('is_del', 0)->orderBy('id', 'desc')->get();
        $result = [];
        foreach ($departments as $department) {
            $result[] = [
                'id' => $department->id,
                'name' => $department->name
            ];
        }
        return $result;
    }

    public static function deleteManager($id)
    {
        $manager = Manager::where('is_del', 0)->where('id', $id)->first();
        if (!$manager) {
            return;
        }
        $manager->is_del = 1;
        $manager->updated_at = date('Y-m-d H:i:s', time());
        $manager->save();
    }

    public static function deleteContest($id)
    {
        $contest = Contest::where('is_del', 0)->where('id', $id)->first();
        if (!$contest) return;
        $contest->is_del = 1;
        $contest->updated_at = date('Y-m-d H:i:s', time());
        $contest->save();
    }

    public static function saveContest($data)
    {
        if (array_key_exists('id', $data)) {
            $contest = Contest::where('id', $data['id'])->first();
        } else {
            $contest = new Contest();
            $contest->type = 2;
            $contest->created_at = date('Y-m-d H:i:s', time());
        }
        foreach ($data as $key => $value) {
            $contest->$key = $value;
        }
        $contest->updated_at = date('Y-m-d H:i:s', time());
        $contest->save();
    }

    public static function getGrowRules($limit, $offset, $type = 0)
    {
        $query = GrowRule::where('is_del', 0);
        if ($type) {
            $query = $query->where('type', $type);
        }
        $total = $query->count();
        $grows = $query->orderBy('id', 'desc')->limit($limit)->offset($offset)->get();
        $result = [];
        foreach ($grows as $grow) {
            $result[] = [
                'id' => $grow->id,
                'title' => $grow->title,
                'realname' => '超级管理员',
                'created_at' => date('Y-m-d H:i:s', strtotime($grow->created_at))
            ];
        }
        return [
            'total' => $total,
            'rows' => $result,
            'limit' => $limit,
            'offset' => $offset,
            'page' => ceil($total / $limit),
            'pageNumber' => $offset / $limit + 1
        ];
    }

    public static function getGrowRuleDetail($id)
    {
        $grow = GrowRule::where('is_del', 0)->where('id', $id)->first();
        if (!$grow) return [];
        return [
            'id' => $grow->id,
            'title' => $grow->title,
            'type' => $grow->type,
            'content' => $grow->content,
            'realname' => $grow->realname,
            'created_at' => date('Y-m-d H:i:s', strtotime($grow->created_at))
        ];
    }

    public static function saveGrowRule($data)
    {
        if (array_key_exists('id', $data)) {
            $grow = GrowRule::where('is_del', 0)->where('id', $data['id'])->first();
        } else {
            $grow = new GrowRule();
            $grow->created_at = date('Y-m-d H:i:s', time());
        }
        foreach ($data as $key => $value) {
            $grow->$key = $value;
        }
        $manager = Manager::where('id', $data['manager_id'])->first();
        $grow->realname = $manager->realname;
        $grow->updated_at = date('Y-m-d H:i:s', time());
        $grow->save();
    }

    public static function deleteGrowRule($id)
    {
        $grow = GrowRule::where('is_del', 0)->where('id', $id)->first();
        if (!$grow) return;
        $grow->is_del = 1;
        $grow->updated_at = date('Y-m-d H:i:s', time());
        $grow->save();
    }

    public static function getUserDetail($id)
    {
        $year = date('Y', time());
        $user = User::where('id', $id)->where('is_del', 0)->first();
        if (!$user) return [];

        $department = Department::where('is_del', 0)->where('id', $user->department_id)->first();
        $departmentName = $department ? $department->name : '';
        $score = 0;
        if ($department) {
            $applyScores = IncreaseScoreApply::where('is_del', 0)->where('role', 1)->where('user_id', $id)->where('department_id', $department->id)->where('created_at', '>=', $year.'-01-01 00:00:00')->get();
            foreach ($applyScores as $applyScore) {
                $score += $applyScore->score;
            }
            $memberScoreFiles = MemberFileScore::where('is_del', 0)->where('role', 1)->where('type', 3)->where('user_id', $id)->where('created_at', '>=', $year.'-01-01 00:00:00')->get();
            foreach ($memberScoreFiles as $memberScoreFile) {
                $score += $memberScoreFile->score*0.9;
            }
        }
        return [
            'id' => $user->id,
            'number' => $user->number,
            'realname' => $user->realname,
            'gender' => gender($user->gender),
            'birthday' => date('Y-m-d', strtotime($user->birthday)),
            'join_party_at' => date('Y-m-d', strtotime($user->join_party_at)),
            'mobile' => $user->mobile,
            'role' => $user->role,
            'role_name' => get_role_name($user->role),
            'education_code' => $user->education_code,
            'education_name' => education($user->education_code),
            'department_id' => $user->department_id,
            'department_name' => $departmentName,
            'score' => $score,
            'summary' => $user->summary,
            'level' => self::getUserYearLevel($id, $year)
        ];
    }

    public static function deleteUser($id)
    {
        $user = User::where('id', $id)->first();
        $user->is_del = 1;
        $user->updated_at = date('Y-m-d H:i:s', time());
        $user->save();
    }

    public static function adviceToUser($uid, $limit, $offset, $year = 0)
    {
        $query = Advice::where('is_del', 0)->where('user_id', $uid)->where('department_id', 0)->where('type', 1);
        if ($year > 0) {
            $next = $year + 1;
            $query->where('created_at', '>=', $year.'-01-01 00:00:00')->where('created_at', '<', $next.'-01-01 00:00:00');
        }
        $total = $query->count();
        $advices = $query->orderBy('id', 'desc')->limit($limit)->offset($offset)->get();
        $result = [];
        foreach ($advices as $advice) {
            $result[] = [
                'department_name' => '',
                'created_at' => date('Y-m-d H:i:s', strtotime($advice->created_at)),
                'content' => $advice->content
            ];
        }
        return [
            'total' => $total,
            'rows' => $result,
            'pages' => ceil($total / $limit),
            'page' => $offset / $limit + 1

        ];
    }

    public static function adviceToDepartment($departmentId, $limit, $offset, $year = 0)
    {
        $query = Advice::where('is_del', 0)->where('department_id', $departmentId)->where('type', 2);
        if ($year > 0) {
            $next = $year + 1;
            $query->where('created_at', '>=', $year.'-01-01 00:00:00')->where('created_at', '<', $next.'-01-01 00:00:00');
        }
        $total = $query->count();
        $advices = $query->orderBy('id', 'desc')->limit($limit)->offset($offset)->get();
        $result = [];
        foreach ($advices as $advice) {
            $result[] = [
                'created_at' => date('Y-m-d H:i:s', strtotime($advice->created_at)),
                'content' => $advice->content
            ];
        }
        return [
            'total' => $total,
            'rows' => $result,
            'pages' => ceil($total / $limit),
            'page' => $offset / $limit + 1

        ];
    }

    public static function saveDepartmentIncrease($id, $score)
    {
        $increase = IncreaseScoreApply::where('id', $id)->first();
        $increase->score = $score;
        $increase->updated_at = date('Y-m-d H:i:s', time());
        $increase->save();
    }

    public static function getUserScoreFile($uid)
    {
        $user = User::where('id', $uid)->first();
        $year = date('Y', time());
        $next = $year + 1;
        $query = ScoreFile::where('is_del', 0)->where('type', 1)->where('created_at', '>=', $year.'-01-01 00:00:00');
        if ($user->role == 5) {
            $query->where('role', 5);
        } else {
            $query->where('role', 1);
        }
        $total = $query->count();
        $files = $query->get();
        $results = [];
        $n = 0;
        foreach ($files as $file) {
            $n ++;
            $fileScores = MemberFileScore::where('score_file_id', $file->id)->where('user_id', $uid)->where('role', 1)->get();
            $score = $selfScore = $juniorScore = 0;
            foreach ($fileScores as $fileScore) {
                if ($fileScore->type == 1 && $fileScore->role == 1) {
                    $selfScore = $fileScore->score;
                }
                if ($fileScore->type == 2 && $fileScore->role == 1) {
                    $juniorScore = $fileScore->score;
                }
                if ($fileScore->type == 3 && $fileScore->role == 1) {
                    $score = $fileScore->score;
                }
            }
            $results[] = [
                'id' => $n,
                'score_file_id' => $file->id,
                'content' => $file->content,
                'self_score' => $selfScore,
                'junior_score' => $juniorScore,
                'secondary_score' => $score,
                'score' => $score
            ];
        }
        $increases = IncreaseScoreApply::where('is_del', 0)->where('user_id', $uid)->where('department_id', $user->department_id)->where('role', 1)->where('created_at', '>=', $year.'-01-01 00:00:00')->where('created_at', '<', $next.'-01-01 00:00:00')->get();
        $score = 0;
        foreach ($increases as $increase) {
            $score += $increase->score;
        }
        $results[] = [
            'id' => 0,
            'content' => '加分中心累计分数: '.$score,
            'score' => $score
        ];
        return [
            'total' => $total,
            'rows' => $results,
            'limit' => 10,
            'offset' => 0,
            'page' => ceil($total / 10),
            'pageNumber' => 1
        ];
    }


    public static function getDepartmentScoreFile($departmentId)
    {
        $year = date('Y', time());
        $next = $year + 1;
        $query = ScoreFile::where('is_del', 0)->where('type', 2)->where('created_at', '>=', $year.'-01-01 00:00:00');
        $total = $query->count();
        $files = $query->get();
        $results = [];
        $n = 0;
        foreach ($files as $file) {
            $n ++;
            $fileScores = MemberFileScore::where('score_file_id', $file->id)->where('department_id', $departmentId)->where('role', 2)->get();
            $score = $selfScore = 0;
            foreach ($fileScores as $fileScore) {
                if ($fileScore->type == 1 && $fileScore->role == 2) {
                    $selfScore = $fileScore->score;
                }
                if ($fileScore->type == 3 && $fileScore->role == 2) {
                    $score = $fileScore->score;
                }
            }
            $results[] = [
                'id' => $n,
                'score_file_id' => $file->id,
                'content' => $file->content,
                'self_score' => $selfScore,
                'secondary_score' => $score,
                'score' => $score
            ];
        }
        $increases = IncreaseScoreApply::where('is_del', 0)->where('department_id', $departmentId)->where('role', 2)->where('created_at', '>=', $year.'-01-01 00:00:00')->where('created_at', '<', $next.'-01-01 00:00:00')->get();
        $score = 0;
        foreach ($increases as $increase) {
            $score += $increase->score;
        }
        $results[] = [
            'id' => 0,
            'content' => '加分中心累计分数: '.$score,
            'score' => $score
        ];
        return [
        'total' => $total,
            'rows' => $results,
            'limit' => 10,
            'offset' => 0,
            'page' => ceil($total / 10),
            'pageNumber' => 1
        ];
    }

    public static function getDepartmentScoreFileDetail($id, $departmentId)
    {
        $file = ScoreFile::where('id', $id)->first();
        $fileScore = MemberFileScore::where('score_file_id', $file->id)->where('type', 3)->where('department_id', $departmentId)->where('role', 2)->first();
        return [
            'id' => $file->id,
            'title' => $file->title,
            'content' => $file->content,
            'refer_score' => $file->score,
            'score' => $fileScore ? $fileScore->score : 0
        ];
    }

    public static function saveUserScoreFileScore($id, $uid, $score)
    {
        $file = ScoreFile::where('id', $id)->first();
        $fileScore = MemberFileScore::where('score_file_id', $file->id)->where('type', 3)->where('user_id', $uid)->where('role', 1)->first();
        if (!$fileScore) {
            $fileScore = new MemberFileScore();
            $fileScore->score_file_id = $file->id;
            $fileScore->user_id = $uid;
            $fileScore->type = 3;
            $fileScore->role = 1;
            $fileScore->created_at = date('Y-m-d H:i:s', time());
        }
        $fileScore->score = $score;
        $fileScore->updated_at = date('Y-m-d H:i:s', time());
        $fileScore->save();
    }

    public static function saveDepartmentScoreFileScore($id, $departmentId, $score)
    {
        $file = ScoreFile::where('id', $id)->first();
        $fileScore = MemberFileScore::where('score_file_id', $file->id)->where('type', 3)->where('department_id', $departmentId)->where('role', 2)->first();
        if (!$fileScore) {
            $fileScore = new MemberFileScore();
            $fileScore->score_file_id = $file->id;
            $fileScore->department_id = $departmentId;
            $fileScore->type = 3;
            $fileScore->role = 2;
            $fileScore->created_at = date('Y-m-d H:i:s', time());
        }
        $fileScore->score = $score;
        $fileScore->updated_at = date('Y-m-d H:i:s', time());
        $fileScore->save();
    }





    public static function getIncreaseScore($limit, $offset, $role = 0, $search = '')
    {
        $query = IncreaseScoreApply::where('is_del', 0);
        if ($role) {
            $query = $query->where('role', $role);
        }
        if ($search) {
            $query->where('title', 'like', "%{$search}%");
        }$total = $query->count();
        $increases = $query->orderBy('id', 'desc')->limit($limit)->offset($offset)->get();
        $result = [];
        foreach ($increases as $increase) {
            $realname = '';
            $name = '';
            if ($role == 1) {
                $user = User::where('id', $increase->user_id)->first();
                $realname = $user ? $user->realname : '';
            }
            if ($role == 2) {
                $department = Department::where('id', $increase->department_id)->first();
                $name = $department ? $department->name : '';
            }
            $result[] = [
                'id' => $increase->id,
                'title' => $increase->title,
                'created_at' => date('Y-m-d H:i:s', strtotime($increase->created_at)),
                'realname' => $realname,
                'name' => $name,
                'score' => $increase->score
            ];
        }
        return [
            'total' => $total,
            'rows' => $result,
            'pages' => ceil($total / $limit),
            'page' => $offset / $limit + 1

        ];
    }

    public static function login($username, $password)
    {
        $manager = Manager::where('username', $username)->where('password', $password)->where('is_del', 0)->first();
        if (!$manager) {
            throw new \Exception('用户名或密码错误，请重试！', 4031);
        }
        $timeout = (int)((time()+7200)/3600)*3600;
        $jwt = new MyJwt();
        $jwt->payload['uid'] = $manager->id;
        $jwt->payload['role'] = $manager->role;
        $jwt->payload['timeout'] = $timeout;
        $jwt->payload['ticket'] = md5($manager->username);
        $jwtCode = $jwt->encode($jwt->payload, MyJwt::ENCODE_KEY);
        return [
            '_token' => $jwtCode,
            'role' => $manager->role
        ];
    }



    public static function updateUserIncreaseScore($data)
    {
        $increase = IncreaseScoreApply::where('is_del', 0)->where('id', $data['id'])->first();
        if ($increase) {
            $increase->score = $data['score'];
            $increase->updated_at = date('Y-m-d H:i:s', time());
            $increase->save();
        }
    }

    public static function updateDepartmentIncreaseScore($data)
    {
        $increase = IncreaseScoreApply::where('is_del', 0)->where('id', $data['id'])->first();
        if ($increase) {
            $increase->score = $data['score'];
            $increase->updated_at = date('Y-m-d H:i:s', time());
            $increase->save();
        }
    }

    public static function deleteIncreaseScore($id)
    {
        $increase = IncreaseScoreApply::where('is_del', 0)->where('id', $id)->first();
        if ($increase) {
            $increase->is_del = 1;
            $increase->updated_at = date('Y-m-d H:i:s', time());
            $increase->save();
        }
    }

    public static function saveAdvice($content, $uid = 0, $departmentId = 0)
    {
        $advice = new Advice();
        $advice->user_id = $uid;
        $advice->department_id = $departmentId;
        $advice->type = $uid > 0 ? 1 : 2;
        $advice->content = $content;
        $advice->created_at = date('Y-m-d H:i:s', time());
        $advice->updated_at = date('Y-m-d H:i:s', time());
        $advice->save();
    }

    public static function scoreFiles($limit, $offset, $type, $year, $role)
    {
        $next = $year + 1;
        $query = ScoreFile::where('is_del', 0)->where('type', $type)->where('created_at', '>=', $year.'-01-01 00:00:00')->where('created_at', '<', $next.'-01-01 00:00:00');
        if ($type == 1) {
            $query = $query->where('role', $role);
        }
        $total = $query->count();
        $files = $query->orderBy('id', 'desc')->limit($limit)->offset($offset)->get();
        $result = [];
        foreach ($files as $file) {
            $result[] = [
                'id' => $file->id,
                'content' => $file->content,
                'score' => $file->score
            ];
        }
        return [
            'total' => $total,
            'rows' => $result,
            'limit' => $limit,
            'offset' => $offset,
            'page' => ceil($total / $limit),
            'pageNumber' => $offset / $limit + 1
        ];
    }

    public static function scoreFileDetail($id)
    {
        $file = ScoreFile::where('id', $id)->first();
        return [
            'id' => $file->id,
            'title' => $file->title,
            'content' => $file->content,
            'score' => $file->score
        ];
    }

    public static function saveScoreFile($data)
    {
        if (array_key_exists('id', $data)) {
            $file = ScoreFile::where('is_del', 0)->where('id', $data['id'])->first();
        } else {
            $file = new ScoreFile();
            $file->created_at = date('Y-m-d H:i:s', time());
        }
        foreach ($data as $key => $value) {
            $file->$key = $value;
        }
        $file->updated_at = date('Y-m-d H:i:s', time());
        $file->save();
    }

    public static function deleteScoreFile($id)
    {
        $file = ScoreFile::where('id', $id)->first();
        if ($file) {
            $file->is_del = 1;
            $file->updated_at = date('Y-m-d H:i:s', time());
            $file->save();
        }
    }

    public static function getUserScoreFileDetail($id, $uid)
    {
        $file = ScoreFile::where('id', $id)->first();
        $fileScore = MemberFileScore::where('score_file_id', $file->id)->where('type', 3)->where('department_id', 0)->where('user_id', $uid)->where('role', 1)->first();
        return [
            'id' => $file->id,
            'title' => $file->title,
            'content' => $file->content,
            'refer_score' => $file->score,
            'score' => $fileScore ? $fileScore->score : 0
        ];
    }

    public static function getDataUsers()
    {
        $users = User::where('is_del', 0)->get();
        $total = count($users);
        $teacher = $scientist = $manager = $assistant = $student = 0;
        foreach ($users as $user) {
            if ($user->role == 1) {
                $teacher ++;
            }
            if ($user->role == 2) {
                $scientist ++;
            }
            if ($user->role == 3) {
                $manager ++;
            }
            if ($user->role == 4) {
                $assistant ++;
            }
            if ($user->role == 5) {
                $student ++;
            }
        }
        return [
            'total' => $total,
            'list' => [
                [
                    'item' => '教学人员',
                    'num' => $teacher,
                    'percent' => round($teacher / $total, 2)
                ],
                [
                    'item' => '科研人员',
                    'num' => $scientist,
                    'percent' => round($scientist / $total, 2)
                ],
                [
                    'item' => '管理人员',
                    'num' => $manager,
                    'percent' => round($manager / $total, 2)
                ],
                [
                    'item' => '教辅人员',
                    'num' => $assistant,
                    'percent' => round($assistant / $total, 2)
                ],
                [
                    'item' => '学生',
                    'num' => $student,
                    'percent' => round($student / $total, 2)
                ]
            ]
        ];
    }

    public static function checkUsername($username)
    {
        $manager = Manager::where('is_del', 0)->where('username', $username)->first();
        if ($manager) {
            return ['repeat' => 1];
        }
         return ['repeat' => 0];
    }

    public static function getUserLevel($uid)
    {
        $year = date('Y', time());
        $next = $year + 1;
        $selfLevel = UserLevel::where('user_id', $uid)->where('department_id', 0)->where('type', 1)->where('created_at', '>=', $year.'-01-01 00:00:00')->where('created_at', '<', $next.'-01-01 00:00:00')->first();
        $user = User::where('id', $uid)->where('is_del', 0)->first();
        $juniorLevel = UserLevel::where('user_id', $uid)->where('department_id', $user->department_id)->where('type', 2)->where('created_at', '>=', $year.'-01-01 00:00:00')->where('created_at', '<', $next.'-01-01 00:00:00')->first();
        $secondaryLevel = UserLevel::where('user_id', $uid)->where('department_id', 0)->where('type', 3)->where('created_at', '>=', $year.'-01-01 00:00:00')->where('created_at', '<', $next.'-01-01 00:00:00')->first();
        return [
            'self_level' => $selfLevel ? ['id' => $selfLevel->id, 'level' => $selfLevel->level] : ['id' => 0, 'levle' => 0],
            'junior_level' => $juniorLevel ? ['id' => $juniorLevel->id, 'level' => $juniorLevel->level] : ['id' => 0, 'levle' => 0],
            'secondary_level' => $secondaryLevel ? ['id' => $secondaryLevel->id, 'level' => $secondaryLevel->level] : ['id' => 0, 'levle' => 0]
        ];
    }

    public static function saveUserLevel($data)
    {
        if (array_key_exists('id', $data)) {
            $level = UserLevel::where('id', $data['id'])->first();
        } else {
            $level = new UserLevel();
            $level->user_id = $data['user_id'];
            $level->department_id = 0;
            $level->type = 3;
            $level->created_at = date('Y-m-d H:i:s', time());
        }
        $level->level = $data['level'];
        $level->updated_at = date('Y-m-d H:i:s', time());
        $level->save();
    }
}